# -*- coding: utf8 -*-

from OpenGL.GL import *
from OpenGL.GLUT import *

from setting import *


def draw_text(value, x,y, width=WINDOW_WIDTH, height=WINDOW_HEIGHT, step=18):
    """
    在屏幕的 x, y 位置显示字符串
    """
    glMatrixMode(GL_PROJECTION)

    # 由于某些原因，不能用 glPushMatrix 来保存 GL_PROJECTION_MATRIX，否则会溢出
    matrix = glGetDouble(GL_PROJECTION_MATRIX)
    glLoadIdentity()

    # 平行投影
    glOrtho(0.0, width, 0.0, height, -1.0, 1.0)

    # glOrtho(0.0, height, 0.0, width, -1.0, 1.0)
    glMatrixMode(GL_MODELVIEW)
    glPushMatrix()
    glLoadIdentity()

    glRasterPos2i(x, y)
    lines = 0
    for character in value:
        if character == '\n':
            glRasterPos2i(x, y-(lines*18))
        else:
            glutBitmapCharacter(GLUT_BITMAP_HELVETICA_18, ord(character))
    glPopMatrix()
    glMatrixMode(GL_PROJECTION)
    glLoadMatrixd(matrix)
    glMatrixMode(GL_MODELVIEW)


def singleton(cls, *args, **kw):
    """单例模式
    """
    instances = {}

    def _singleton(*args, **kw):
        if cls not in instances:
            instances[cls] = cls(*args, **kw)
        return instances[cls]

    return _singleton